import editForm from "../form.vue";
import { message } from "@/utils/message";
import {
  queryProducePaperList,
  updateProducePaperStatus,
  deleteProducePaper,
  addOrUpdateProducePaper
} from "@/api/exam";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { addDialog, closeDialog } from "@/components/ReDialog";
import { type FormItemProps } from "../utils/types";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, h } from "vue";

export function useRole() {
  const searchForm = reactive({
    name: "",
    del: "0"
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      minWidth: 30,
      type: "index",
      index: (index: number) => {
        return (pagination.currentPage - 1) * pagination.pageSize + (index + 1);
      }
    },
    {
      label: "试卷名称",
      prop: "name",
      minWidth: 140
    },
    {
      label: "试卷类型",
      prop: "type",
      minWidth: 80,
      formatter: row => {
        switch (row.type) {
          case 0:
            return "固定题型";
          case 1:
            return "随机题型";
        }
      }
    },
    {
      label: "考试时长",
      prop: "times",
      minWidth: 100,
      formatter: row => {
        return `${row.times}(分钟)`;
      }
    },
    {
      label: "试卷分数",
      prop: "score",
      minWidth: 100,
      formatter: row => {
        return `${row.score}分`;
      }
    },
    {
      label: "试卷状态",
      prop: "del",
      minWidth: 60,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.del}
          active-value={0}
          inactive-value={1}
          active-text="已开启"
          inactive-text="已关闭"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "创建时间",
      prop: "addtime",
      minWidth: 100
    },
    {
      label: "操作",
      fixed: "right",
      width: 150,
      slot: "operation"
    }
  ];

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.del === 1 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.name
      }</strong>试卷吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        updateProducePaperStatus({
          id: row.id,
          del: row.del
        })
          .then(res => {
            if (res.success) {
              message("已成功修改试卷状态", { type: "success" });
              onSearch();
              switchLoadMap.value[index] = Object.assign(
                {},
                switchLoadMap.value[index],
                {
                  loading: false
                }
              );
            } else {
              row.del === 0 ? (row.del = 1) : (row.del = 0); //异常状态恢复
              message("修改状态异常:" + res.errMsg, { type: "error" });
            }
          })
          .catch(error => {
            row.del === 0 ? (row.del = 1) : (row.del = 0); //异常状态恢复
            message("修改状态异常:" + JSON.stringify(error), { type: "error" });
          });
      })
      .catch(() => {
        row.del === 0 ? (row.del = 1) : (row.del = 0); //状态恢复
      });
  }

  function handleDelete(row) {
    deleteProducePaper(row)
      .then(res => {
        if (res.success) {
          message(`您删除了试卷名称为"${row.name}"的这条数据`, {
            type: "success"
          });
          onSearch();
        } else {
          message("删除数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("删除数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    queryProducePaperList({
      name: searchForm.name,
      del: searchForm.del,
      pageSize: pagination.pageSize,
      currentPage: pagination.currentPage
    })
      .then(res => {
        if (res.success) {
          dataList.value = res.data.list;
          pagination.total = res.data.total;
          loading.value = false;
        } else {
          message("查询数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("查询数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}试卷`,
      props: {
        formInline: {
          id: row?.id ?? "",
          creater: row?.creater ?? "",
          name: row?.name ?? "",
          type: row?.type ?? 0,
          times: row?.times ?? 90,
          score: row?.score ?? 0,
          del: row?.del ?? 0,
          addtime: row?.addtime ?? "",
          updatetime: row?.updatetime ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      footerButtons: [
        {
          label: "取消",
          type: "info",
          btnClick: ({ dialog: { options, index } }) => {
            closeDialog(options, index);
          }
        },
        {
          label: "确定",
          type: "success",
          btnClick: ({ dialog: { options, index } }) => {
            const FormRef = formRef.value.getRef();
            const ScoreRef = formRef.value.getScoreRef();
            const QuestionRef = formRef.value.getQuestionRef();
            const curData = options.props.formInline as FormItemProps;
            function chores() {
              message(`您${title}了试卷名称为"${curData.name}"的这条数据`, {
                type: "success"
              });
              closeDialog(options, index); // 关闭弹框
              onSearch(); // 刷新表格数据
            }
            FormRef.validate(valid => {
              if (valid) {
                addOrUpdateProducePaper({
                  ...curData,
                  scoreList: ScoreRef,
                  questionList: QuestionRef
                })
                  .then(res => {
                    if (res.success) {
                      chores();
                    } else {
                      message("提交失败:" + res.errMsg, { type: "error" });
                    }
                  })
                  .catch(error => {
                    message("提交失败:" + JSON.stringify(error), {
                      type: "error"
                    });
                  });
              }
            });
          }
        }
      ]
    });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    searchForm,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
